package com.liu.security.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liu.security.exception.CustomException;
import com.liu.security.pojo.http.ApiResponse;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class ResponseUtils {

    public static void endResponse(HttpServletResponse response, CustomException customException) throws IOException {
        response.setStatus(customException.getCode());
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 创建返回的 JSON 信息
        ApiResponse<Object> objectApiResponse = new ApiResponse<>(customException.getMessage(), null, customException.getCode());
        // 将 JSON 写入响应体
        PrintWriter out = response.getWriter();
     /*   ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(objectApiResponse);*/
        out.print(JSON.toJSONString(objectApiResponse));
        log.info("返回信息：{}", JSON.toJSONString(objectApiResponse));
        out.flush();
    }
}
